﻿using System;
using System.Reflection.Emit;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.cbuilder.MSILSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder
{
    internal class StoreArrayElementTranslator : ITranslator {

        private static void CheckInstruction(Instruction inst) {
            if(inst.Inst != OpCodes.Stelem_I &&
               inst.Inst != OpCodes.Stelem_I1 &&
               inst.Inst != OpCodes.Stelem_I2 &&
               inst.Inst != OpCodes.Stelem_I4 &&
               inst.Inst != OpCodes.Stelem_I8 &&
               inst.Inst != OpCodes.Stelem_R4 &&
               inst.Inst != OpCodes.Stelem_R8) {
                   throw new Exception("unknown instruction: " + inst);
               }
        }

        public ICStatement TranslateAndAdd(CMethodBody methodBody, CBasicBlock currentBlock, BasicBlock block, Instruction instruction) {
            CheckInstruction(instruction);
            IVariable valueVar = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            IVariable indexVar = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            IVariable arrayVar = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            StoreArrayElementStatement stm = new StoreArrayElementStatement(arrayVar, indexVar, valueVar);
            currentBlock.Statements.Add(stm);
            return stm;
        }
    }
}